<?php

namespace app\api\controller\coupons;
use app\common\controller\Api;
use addons\third\model\Third;
use app\api\controller\coupons\Basic;
use think\Db;
use think\Config;

header('Access-Control-Allow-Origin:*');//允许跨域
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Headers:x-requested-with,content-type,token');
    //浏览器页面ajax跨域请求会请求2次，第一次会发送OPTIONS预请求,不进行处理，直接exit返回，但因为下次发送真正的请求头部有带token
    //所以这里设置允许下次请求头带token否者下次请求无法成功
    exit();
}

/**
 * 基本类，初始化请求
 * Class Base
 * @package app\api\controller\moyi
 */

class Base extends Api
{

    protected $noNeedLogin = ['myCouponListsByUID','myCouponCountByUID','createAutoCoupon','getQrCode','getAccessToken','isExpires','areaJson','couponAutoExpired','saveAll','AppointmentAutoExpired','createAutoClinicAccount'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('third');
        $this->user_id = $this->auth->id;
    }


     /**
     * 获取我的预约和订单数量
     *
     * @param string $type 1代表查询数量，2代表查询预约的具体列表，3代表查询订单的数据列表,type=2或者3必传page
     */
    public function mydata($type=1,$page=0,$limit=10)
    {
          $user_id=$this->user_id; 
          $limit=$limit?$limit:10;
          if($type==1){
            $myAppointment=Db::name('coupons_appointment')->where('user_id',$user_id)->count();
            $myOrder=Db::name('coupons_order')->page($page,$limit)->order('createtime','desc')->count();
            $data['myAppointment']=$myAppointment;
            $data['myOrder']=$myOrder;
          }else if($type==2){
             $myAppointment=Db::name('coupons_appointment')->page($page,$limit)->order('createtime','desc')->select();
             $data['myAppointment']=$myAppointment;
          }else if($type==3){
              $myOrder=Db::name('coupons_order')->page($page,$limit)->order('createtime','desc')->select();
              $data['myOrder']=$myOrder;
          }else{
            $data=[];
          }
          return $data;

    }

 /**
     * 获取我的优惠券
     *
     * @param string $type -1代表全部，0代表未使用，1代表已预约,2代表已完成 
     * @param string $all  代表返回全部的优惠券数据
     */
    public function myCouponLists($type='-1',$page=0,$limit=10,$all=0)
    {   
          $limit=$limit?$limit:10;  
          //数据有几部分匹配而来。1.积分商城：匹配条件unionid  2.hr系统   ：匹配条件 staffnumber
          $user_id=$this->auth->id;
          //查员工的工号
          $staffnumber=Db::name('user')->where('id',$user_id)->value('staffnumber');
          //查员工的unionid 匹配
          $unionid = Third::where(['user_id' => $user_id, 'platform' => 'wechat'])->value('unionid');
          //$where['A.user_id']=array('eq',$user_id); 
          $whereOr=[];$where=[];
          if($unionid && $staffnumber){
            $whereOr = [
                          'A.unionid' => $unionid,
                          'A.staffnumber' =>$staffnumber,
                      ];
          }else if($unionid){
            $where['A.unionid'] = array('eq' , $unionid);
        }else if($staffnumber){
            $where['A.staffnumber'] = array('eq' , $staffnumber);
          }else{
            $where['A.id']=array('eq',0);
          } 
          if($type!=-1){
            $where['A.statusdata']=$type;
          }else{
            $where['A.statusdata']=array('in','0,1,2,3,4');
          }
          
          //var_dump($where);exit;
          if($all==0){
             $myCouponLists=Db::name('coupons')
                        ->alias('A')
                        ->join('coupons_category B', 'A.coupon_category_id = B.id')
                        ->where($where)
                        ->where(function($query) use ($whereOr){
                              $query->whereOr($whereOr);
                          })
                        ->field("A.*,B.nametext as category_name,B.descriptioncontent,B.coverpicimage,B.pricenumber,B.effective,from_unixtime(A.begintime,'%Y-%m-%d %H:%i:%s') as begintime,from_unixtime(A.endtime,'%Y-%m-%d %H:%i:%s') as endtime")
                        //->fetchSql(true)
                        //->page($page,$limit)
                        ->order('createtime','desc')
                        ->page($page,$limit)
                        ->select();
              }else{

                 $myCouponLists=Db::name('coupons')
                        ->alias('A')
                        ->join('coupons_category B', 'A.coupon_category_id = B.id')
                        ->where($where)
                        ->where(function($query) use ($whereOr){
                              $query->whereOr($whereOr);
                          })
                        ->field("A.*,B.nametext as category_name,B.descriptioncontent,B.coverpicimage,B.pricenumber,B.effective,from_unixtime(A.begintime,'%Y-%m-%d %H:%i:%s') as begintime,from_unixtime(A.endtime,'%Y-%m-%d %H:%i:%s') as endtime")
                        ->order('createtime','desc')
                        //->page($page,$limit)
                        ->select();

                      }
         //查询是否预约，给个标识
          foreach ($myCouponLists as $key => $value) {
            if($value['statusdata']==0){
              $couponAoopintment=Db::name('coupons_appointment')->where(['coupon_id'=>$value['id'],'user_id'=>$user_id])->order('id desc')->select();
             //var_dump($couponAoopintment);
              if($couponAoopintment){
                    if($couponAoopintment[0]['statuslist']==0){
                        $myCouponLists[$key]['appointmentStatus']=0;//提交
                    }else if($couponAoopintment[0]['statuslist']==1)
                    {
                       $myCouponLists[$key]['appointmentStatus']=1;//通过
                    }else{
                       $myCouponLists[$key]['appointmentStatus']=2;//未通过
                    }
              }else{
                   $myCouponLists[$key]['appointmentStatus']=-1;//未提交
              }
            }
            
          }
          //C.name as clinic_name,C.addresstext,C.longitudetext,C.latitudetext,C.phonetext,C.logoavatar,C.coverpicimages as clinci_images,C.qrcodeimage, 
          //当状态为未使用的时候，是没有关联门店的，所以就没有门店信息，过期或者作废的不一定信息，所以通过循环找是否有门店信息
         
          return $myCouponLists;

    }

    /**
     * 获取我的优惠券
     *
     * @param string $type -1代表全部，0代表未使用，1代表已预约,2代表已完成 
     * @param string $all  代表返回全部的优惠券数据
     */
    public function myCouponListsByUID($unionid,$type='-1',$page=0,$limit=10,$all=0)
    {   
          $limit=$limit?$limit:10;  
          //数据有几部分匹配而来。1.积分商城：匹配条件unionid  2.hr系统   ：匹配条件 staffnumber
         
          //$where['A.user_id']=array('eq',$user_id); 
          $whereOr=[];$where=[];
           if($unionid){
            $where['A.unionid'] = array('eq' , $unionid);
           }else{
            $where['A.id']=array('eq',0);
          } 
          if($type!=-1){
            $where['A.statusdata']=$type;
          }else{
            $where['A.statusdata']=array('in','0,1,2,3,4');
          }
          
          //var_dump($where);exit;
          if($all==0){
             $myCouponLists=Db::name('coupons')
                        ->alias('A')
                        ->join('coupons_category B', 'A.coupon_category_id = B.id')
                        ->where($where)
                        ->where(function($query) use ($whereOr){
                              $query->whereOr($whereOr);
                          })
                        ->field("A.*,B.nametext as category_name,B.descriptioncontent,B.coverpicimage,B.pricenumber,B.effective,from_unixtime(A.begintime,'%Y-%m-%d %H:%i:%s') as begintime,from_unixtime(A.endtime,'%Y-%m-%d %H:%i:%s') as endtime")
                        //->fetchSql(true)
                        //->page($page,$limit)
                        ->order('createtime','desc')
                        ->page($page,$limit)
                        ->select();
              }else{

                 $myCouponLists=Db::name('coupons')
                        ->alias('A')
                        ->join('coupons_category B', 'A.coupon_category_id = B.id')
                        ->where($where)
                        ->where(function($query) use ($whereOr){
                              $query->whereOr($whereOr);
                          })
                        ->field("A.*,B.nametext as category_name,B.descriptioncontent,B.coverpicimage,B.pricenumber,B.effective,from_unixtime(A.begintime,'%Y-%m-%d %H:%i:%s') as begintime,from_unixtime(A.endtime,'%Y-%m-%d %H:%i:%s') as endtime")
                        ->order('createtime','desc')
                        //->page($page,$limit)
                        ->select();

                      }
         
          //C.name as clinic_name,C.addresstext,C.longitudetext,C.latitudetext,C.phonetext,C.logoavatar,C.coverpicimages as clinci_images,C.qrcodeimage, 
          //当状态为未使用的时候，是没有关联门店的，所以就没有门店信息，过期或者作废的不一定信息，所以通过循环找是否有门店信息
         
          return $myCouponLists;

    }

    /**
     * 获取我的优惠券数量
     *
     * 优惠券使用状态:0=未使用,1=已预约,2=已使用,3=已过期,4=已作废
     */
    public function myCouponCount()
    {
            $user_id=$this->user_id; 
             $user_id=$this->auth->id;
          //查员工的工号
            $staffnumber=Db::name('user')->where('id',$user_id)->value('staffnumber');
            //查员工的unionid 匹配
            $unionid = Third::where(['user_id' => $user_id, 'platform' => 'wechat'])->value('unionid');
            //$where['A.user_id']=array('eq',$user_id); 
            $whereOr=[];$where=[];
            if($unionid && $staffnumber){
              $whereOr = [
                          'unionid' => $unionid,
                          'staffnumber' =>$staffnumber,
                      ];
            }else if($unionid){
              $where['unionid'] = array('eq' , $unionid);
          }else if($staffnumber){
              $where['staffnumber'] = array('eq' , $staffnumber);
            }else{
              $where['id']=array('eq',0);
            }  
            $myCouponCount['all']=Db::name('coupons')->where($where)->where('statusdata','in','0,1,2,3,4')
                                  ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
            $myCouponCount['notuse']=Db::name('coupons')->where($where)->where('statusdata','eq','0')
                                    ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
            $myCouponCount['appointment']=Db::name('coupons')->where($where)->where('statusdata','eq','1')
                                    ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
            $myCouponCount['finished']=Db::name('coupons')->where($where)->where('statusdata','eq','2')
                                        ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
          $myCouponCount['outDate']=Db::name('coupons')->where($where)->where('statusdata','in','3,4')
                                        ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
          return $myCouponCount;

    }

    /**
     * 获取我的优惠券数量
     *
     * 优惠券使用状态:0=未使用,1=已预约,2=已使用,3=已过期,4=已作废
     */
    public function myCouponCountByUID($unionid)
    {
           
            $whereOr=[];$where=[];
            if($unionid){
              $where['unionid'] = array('eq' , $unionid);
            }else{
              $where['id']=array('eq',0);
            }  
            $myCouponCount['all']=Db::name('coupons')->where($where)->where('statusdata','in','0,1,2,3,4')
                                  ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
            $myCouponCount['notuse']=Db::name('coupons')->where($where)->where('statusdata','eq','0')
                                    ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
            $myCouponCount['appointment']=Db::name('coupons')->where($where)->where('statusdata','eq','1')
                                    ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
            $myCouponCount['finished']=Db::name('coupons')->where($where)->where('statusdata','eq','2')
                                        ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
          $myCouponCount['outDate']=Db::name('coupons')->where($where)->where('statusdata','in','3,4')
                                        ->where(function($query) use ($whereOr){
                                      $query->whereOr($whereOr);
                                  })
                                  ->count();
          return $myCouponCount;

    }
     /**
     * 优惠券详情
     *
     * @param string $id 优惠券的id
     */
    public function couponDetails($id,$number,$type=0)
    {     

        if($id && $number){
            $couponDetails=Db::name('coupons')->where(['id'=>$id])->find();
        }else{
          if($id){
             $couponDetails=Db::name('coupons')->where('id',$id)->find();
          }else if($number){
             $couponDetails=Db::name('coupons')->where('number',$number)->find();
          }else{
             $couponDetails=[];
          } 
        } 
          
           //var_dump($couponDetails);exit;
            if(!$couponDetails){
               $this->error('优惠券不存在');
            }

            $couponDetails['clinic_detail']='';
            //已关联门店，则查出 门店信息
            if($couponDetails['clinic_id']){
              $couponDetails['clinic_detail']=Db::name('coupons_clinic')->where('id',$couponDetails['clinic_id'])->field('id,name,addresstext,phonetext,logoavatar,coverpicimages')->find();
            }
            //查询优惠券的类型的基本信息
            if($couponDetails['coupon_category_id']){
              $couponDetails['coupon_category_id']=Db::name('coupons_category')->where('id',$couponDetails['coupon_category_id'])->field('id,nametext,descriptioncontent,coverpicimage,pricenumber,group_ids,effective')->find();
            }
            //所有人的基本信息
            if($couponDetails['unionid']){//优惠券过来的用户信息
              $couponDetails['userinfo']=Db::name('third')
                                        ->alias('A')
                                        ->join('user B', 'A.user_id = B.id')
                                        ->where('unionid',$couponDetails['unionid'])
                                        ->field("A.unionid,A.openid,B.avatar,B.username,B.realname,B.id,B.mobile,B.group_id")
                                        ->find();
            }elseif($couponDetails['staffnumber']){//员工信息
               $staffId=Db::name('coupons_user_staff')->where('staffnumber',$couponDetails['staffnumber'])->value('id');
               //var_dump($staffId);exit;
               if($staffId){
                 $couponDetails['userinfo']=Db::name('coupons_bind')
                                        ->alias('A')
                                        ->join('user B', 'A.user_id = B.id')
                                        ->where('number',$staffId)
                                        ->field("A.number as staffnumber,B.avatar,B.nickname,B.realname,B.id,B.mobile,B.group_id")
                                        ->find();
               }else{
                $this->error('该优惠券所有者不存在');
               }
              

            }else{
              $this->error('该优惠券所有者不存在');
            }
             //var_dump($couponDetails);exit;  
            if(!$couponDetails['userinfo']){
              $this->error('该优惠券所有者不存在');
            }
            //预约状态信息查询
             //如果有预约信息，返回预约的门店信息给到用户
             $couponDetails['appointmentInfo']=[];
             $couponAoopintment=Db::name('coupons_appointment')
                                ->alias('A')
                                ->join('coupons_clinic B','A.clinic_id=B.id')
                                ->where(['A.coupon_id'=>$couponDetails['id']])
                                ->field("A.user_id,A.realname,A.statuslist,A.phonetext,A.clinic_id,A.coupon_id,from_unixtime(A.appointmenttime,'%Y年%m月%d日 %H:%i') as appointmenttime,B.name as clinic_name,B.addresstext")
                                ->order('A.id desc')
                                ->select();
              //var_dump($couponAoopintment);exit;
              if($couponAoopintment){
                    if($couponAoopintment[0]['statuslist']==0){
                        $couponDetails['appointmentStatus']=0;//待审核
                    }else if($couponAoopintment[0]['statuslist']==1)
                    {
                       $couponDetails['appointmentStatus']=1;//通过
                    }else{
                       $couponDetails['appointmentStatus']=2;//拒绝
                    }
                    $couponDetails['appointmentInfo']=$couponAoopintment[0];
                     $couponDetails['userinfo']['realname']=$couponAoopintment[0]['realname'];
                     $couponDetails['userinfo']['mobile']=$couponAoopintment[0]['phonetext'];
              }else{
                   $couponDetails['appointmentStatus']=-1;//未查询到相关预约信息
              }
            //自己查看，需要判断是否是该优惠券的所有者
          if($type==0){
              $user_id=$this->user_id; 
              if($user_id!=$couponDetails['userinfo']['id']){
                $this->error('您不是优惠券所有者，无法查看该优惠券');
              }
           }
           //工作人员查看该优惠券
            if($type==1){
                 $user_id=$this->user_id; 
                //先判断是否绑定了
                if($couponDetails['clinic_id']){
                  //判断是否是门店员工或者管理员
                  $coupon_staffs=$this->isClinicStaff($user_id,$couponDetails['clinic_id']);

                }else{
                   $this->error('该优惠券暂未关联使用门店');
                }
             
                         
               if($couponDetails['statusdata']==2){
                     $couponDetails['errmsg']="该优惠券已核销，无法再次核销"; 
                }
                if($couponDetails['statusdata']==3){
                     $couponDetails['errmsg']="该优惠券已过期"; 
                }
                if($couponDetails['statusdata']==4){
                    $couponDetails['errmsg']="该优惠券已作废"; 
                }
              }
          return $couponDetails;

    }
  /**
     * 判断是否是门店员工或者管理员
     *  @param string $user_id  用户id
     */
    public function isClinicStaff($user_id,$clinic_id,$isadmin=0){

            $coupon_staffs=Db::name('coupons_clinic_staff')->where(['coupon_clinic_id'=>$clinic_id,'authorizedata'=>'1'])->column('user_id');
           
             //管理员是后台绑定的，要单独查询
             $clinic_admin=Db::name('coupons_clinic')->where(['id'=>$clinic_id])->value('user_id');
             if($isadmin==1){
              if($user_id!=$clinic_admin){
                $this->error('您不是该门店员工或管理员');
              }
             }
             //var_dump(in_array($user_id,$coupon_staffs));exit;
             //扫码访问的人是否是绑定门店的审核通过的员工
             
           if(in_array($user_id,$coupon_staffs)  || $user_id==$clinic_admin){
             
           }else{
            $this->error('您不是该门店员工或管理员');
           }
    }   
    /**
     * 获取我的预约列表
     *  @param string $page   页数
     *  @param string $limit  每页数量
     */
    public function myAppointment($type='',$clinic_id=0,$page,$limit){
          $user_id=$this->user_id; 
          if($type==1){
            $where['A.user_id']= $user_id;
          }else if($type==2){
             $where['A.clinic_id']= $clinic_id;
             $coupon_staffs=$this->isClinicStaff($user_id,$clinic_id);
          }else{
             $this->error('type参数错误');
          }
           $myAppointmentLists=Db::name('coupons_appointment')
                              ->alias('A')
                              ->join('coupons_clinic B','A.clinic_id = B.id')
                              ->where($where)
                              ->page($page,$limit)
                              ->order('A.id desc')
                              ->field("A.id,A.user_id,A.realname,A.phonetext,A.coupon_id,from_unixtime(A.appointmenttime,'%Y-%m-%d %H:%i') as appointmenttime,from_unixtime(A.createtime,'%Y-%m-%d %H:%i') as createtime,A.clinic_id,A.contenttext,A.statuslist,B.name")
                              ->select();
            foreach ($myAppointmentLists as $key => $value) {
               $myAppointmentLists[$key]['number']='';
               $myAppointmentLists[$key]['coupon_name']='';
               $coupon_info=Db::name('coupons')->where(['id'=>$value['coupon_id']])->field('coupon_category_id,number')->find();
               if($coupon_info){
                 $myAppointmentLists[$key]['number']=$coupon_info['number'];
                 $myAppointmentLists[$key]['coupon_name']=Db::name('coupons_category')->where(['id'=>$coupon_info['coupon_category_id']])->value('nametext');
               }
              
            }
           return $myAppointmentLists;
    }

    /**
     * 门店人员核销优惠券子方法
     *
     * @param string $id 优惠券的id
     * @param string $updateThird 更新三方  1  有unionid 已更新，0 无需更新，直接改优惠券状态
     */
    public function verifyCoupon($number,$updateThird=1)
    {      
           //只要进入这个接口，代表三方的更新已经完成
           //记录一下这个操作，如果有问题，可以排查比对
            $datalog['updateThirdlist']=$updateThird;
            $datalog['coupon_num']=$number;
            $datalog['updatetime']=time();
            //log表先记录下三方更新成功了
            $updateThirdLog = new \app\admin\model\coupons\Log();
            $hasLog=Db::name('coupons_log')->where('coupon_num',$number)->find();
            if($hasLog){
              $couponLog=Db::name('coupons_log')->where('id',$hasLog['id'])->update($datalog);  
            }else{
               $datalog['createtime']=time();
               $couponLog=$updateThirdLog->allowField(true)->save($datalog);
            }
            $couponDetails=Db::name('coupons')->where(['number'=>$number])->find();
            if($couponDetails){
            
          
             if($couponDetails['statusdata']==2){
              $this->error('该优惠券已使用',['errcode'=>0]);
            }
             if($couponDetails['statusdata']==3){
              $this->error('该优惠券已过期',['errcode'=>0]);
            }
             if($couponDetails['statusdata']==4){
              $this->error('该优惠券已作废',['errcode'=>0]);
            }
            if($couponDetails['statusdata']==''){
              $this->error('优惠券状态异常',['errcode'=>0]);
            }
            $has=Db::name('coupons_order')->where('unionid',$couponDetails['unionid'])->whereTime('finishtime', 'today')->find();
            if($has){
              $this->error('优惠券今天已使用过，请明天再使用',['errcode'=>0]);
            }
            //验证优惠券是否过期
            $nowTime=time();
            if($couponDetails['begintime']==0 || $couponDetails['endtime']==0 ){
               $this->error('该优惠券的开始和结束使用时间设置异常',['errcode'=>0]);
            }
            if($couponDetails['begintime']>$nowTime || $couponDetails['endtime']<$nowTime){
                  $this->error('该优惠券不在设定的使用时间范围内',['errcode'=>0]);
            }
          }else{
            $this->error('优惠券不存在',['errcode'=>0]);
          }
           
           
            //工作人员核销该优惠券
              $user_id=$this->user_id; 
              //先判断是否绑定了
              if($couponDetails['clinic_id']){
                  $coupon_staffs=$this->isClinicStaff($user_id,$couponDetails['clinic_id']);
                  //扫码访问的人是否是绑定门店的审核通过的员工或者管理员
                  $data['statusdata']=2;
                  $data['finishtime']=time();
                  $data['user_id']=$user_id;
                   //生成关联门店的订单数据
                  $coupon_info=Db::name('coupons')->where('number',$number)->find();
                  $coupon_category_info=Db::name('coupons_category')->where('id',$coupon_info['coupon_category_id'])->find();
                 
                  $datas=[                        
                        'coupon_category_id'=>$coupon_info['coupon_category_id'],
                        'coupon_id'=>$coupon_info['id'],
                        'coupon_clinic_id'=>$coupon_info['clinic_id'],
                        'user_id'=>$coupon_info['user_id'],
                        'createtime'=>time(),
                        'finishtime'=>time(),
                        'statusdata'=>1,
                        'username'=>$coupon_info['username'],
                        'phonenumber'=>$coupon_info['phonenumber'],
                        'finance_sn'=>$coupon_info['finance_sn'],
                        'pricenumber'=>$coupon_category_info['pricenumber'],
                        'unionid' =>$coupon_info['unionid']
                             ]; 

                  $datas['order']=$this->makeOrderNo();
                   //先查是否生成了优惠券订单，没有的就新增，有的话就更新
                  $hasOrder=Db::name('coupons_order')->where('coupon_id',$coupon_info['id'])->find();
                  if($hasOrder){
                    unset($datas['order']);
                    $orderCoupon=Db::name('coupons_order')->where('id',$hasOrder['id'])->update($datas);  
                    $datass['coupon_order_id']=$hasOrder['id'];
                    $datass['statuslist']=1;
                    $appointmentUpdate=Db::name('coupons_appointment')->where('coupon_id',$coupon_info['id'])->update($datass);
                  }else{
                     $order = new \app\admin\model\coupons\Order();
                    try { 
                          $orderCoupon=$order->allowField(true)->save($datas);
                           $datass['coupon_order_id']=$order->id;
                           $datass['statuslist']=1;
                           $appointmentUpdate=Db::name('coupons_appointment')->where('coupon_id',$coupon_info['id'])->update($datass);
                            Db::commit();
                        } catch (ValidateException $e) {
                            Db::rollback();
                        } catch (PDOException $e) {
                            Db::rollback();
                        } catch (Exception $e) {
                            Db::rollback();
                        }
                  }
                   //核销人员的id也记录下来，便于追溯
                  $verifyCoupon=Db::name('coupons')->where('number',$number)->update($data);
                  //log表本地更新状态也更新为已更新
                  $datalogss['updateLocallist']=1;
                  $couponLog=Db::name('coupons_log')->where('coupon_num',$number)->update($datalogss);  
                  //
                  if($verifyCoupon && $orderCoupon){
                    //对接财务系统
                    $order=Db::name('coupons_order')->where('coupon_id',$coupon_info['id'])->find();
                    self::finance($order);

                    $this->success('核销成功');
                  }else{
                    $this->error('核销失败，请重试',['errcode'=>1]);
                  }
                 
                 
              }else{
                 $this->error('该优惠券暂未关联使用门店',['errcode'=>0]);
              }

    }
    /**
     * 核销后对接财务系统
     *
     * @return void
     */
    public static function finance($order){
      if(!$order['finance_sn']){
        $this->error('财务系统单号不能为空',['errcode'=>0]);
      }
      $params=[
        'finance_sn'=>$order['finance_sn'],
        'username'=>$order['username'],
        'phonenumber'=>$order['phonenumber'],
        'pricenumber'=>$order['pricenumber']
      ];
      
      Http::sendRequest("http://tp.tsletu.com/finance/coupon", $params, 'POST',["Content-type: application/json"]); 
    }
    /**
     * 生成随机订单号
     *
     * @return void
     */
    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date('d') .
            substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

     /**
     * 门店管理员或者员工主页数据
     */
    public function myClinicInfo()
    {       
            $user_id=$this->user_id; 
            $coupon_clinic_admin=Db::name('coupons_clinic')->where(['user_id'=>$user_id])->find();
            $coupon_clinic_staff=Db::name('coupons_clinic_staff')->where(['user_id'=>$user_id])->find();
            if($coupon_clinic_admin){
                 $clinicInfo['user_type']=1;//代表是门店管理员
                 $clinicInfo['id']=$coupon_clinic_admin['id'];//代表是门店管理员
                 $clinicInfo['qrcodeimage']=$coupon_clinic_admin['qrcodeimage'];//代表是门店管理员
                 $clinicInfo['name']=$coupon_clinic_admin['name'];
                 $clinicInfo['addresstext']=$coupon_clinic_admin['addresstext'];
            }else{
              if($coupon_clinic_staff){
                $clinicInfo['user_type']=2;//代表是门店的员工
                $coupon_clinic=Db::name('coupons_clinic')->where(['id'=>$coupon_clinic_staff['coupon_clinic_id']])->find();
                $clinicInfo['id']=$coupon_clinic['id'];//代表是门店管理员
                 $clinicInfo['qrcodeimage']=$coupon_clinic['qrcodeimage'];//代表是门店管理员
                 $clinicInfo['name']=$coupon_clinic['name'];
                 $clinicInfo['addresstext']=$coupon_clinic['addresstext'];
              }else{
                $clinicInfo['user_type']=0;//代表非门店员工，普通用户
              }
                
            }
          //代表是门店的用户
          if($clinicInfo['user_type']==1 ||  $clinicInfo['user_type']==2){
            if($clinicInfo['user_type']==1){
              $clinicInfo['num']['staff']=Db::name('coupons_clinic_staff')->where(['coupon_clinic_id'=>$coupon_clinic_admin['id'],'authorizedata'=>'1'])->count();
            }
            if($clinicInfo['user_type']==2){
              $clinicInfo['num']['staff']=0;
             }
            $clinicInfo['num']['appointment']=Db::name('coupons_appointment')->where(['clinic_id'=>$coupon_clinic_admin['id']])->count();
            $coupon_clinic=Db::name('coupons_clinic')->where(['id'=>$coupon_clinic_staff['coupon_clinic_id']])->find();
            $clinicInfo['num']['order']=Db::name('coupons_order')->where(['coupon_clinic_id'=>$clinicInfo['id']])->count();
            
          }
          //var_dump($clinicInfo);exit;
          return $clinicInfo;

              

    }

   /**
     * 门店列表
      * 门店列表
     *  @param string $id     优惠券id
     *  @param string $lat    当前用户的纬度
     *  @param string $lng    当前用户的精度
     *  @param string $order  排序规则
     *  @param string $page   页数
     *  @param string $limit  每页数量
     *  @param string $province  省份id
     *  @param string $city  城市id
     *  @param string $area  区域id
     */
    public function clinicLists($coupon_id,$page,$limit=10,$order='id asc',$province=null,$city=null,$area=null,$lat=null,$lng=null)
    {      
            //是否返回附近门店数据，默认只返回最近五条
            $categoryCoupon=Db::name('coupons')
                           ->alias('A')
                           ->join('coupons_category B', 'A.coupon_category_id = B.id')
                           ->where(['A.id'=>$coupon_id])
                           ->field("A.id as couponId,A.platform,B.id as categoryCouponId,B.nametext,B.descriptioncontent,B.group_ids")//group_ids 判断是给普通用户可兑换还是给员工，还是给两者都可兑换,对应优惠券的字段platform，1普通，2员工
                           ->find();
             
            if($categoryCoupon){
               $group_ids=explode(',',$categoryCoupon['group_ids']);
               // var_dump($group_ids);exit;
               //当前要使用的优惠券所生成的平台  在这个类型的优惠券所使用的group_id里面，则代表可能有数据，否则就没有数据
               //platform 是唯一的，是生成优惠券的时候带过来的，1代表普通，2代表员工
                 if(in_array($categoryCoupon['platform'],$group_ids)){
                  //分页数据//1门店开启，2 关闭
                  $where['statuslist']=array('eq','1');
                  //符合基础条件的门店数量总数
                   $clinicLists['total']=Db::name('coupons_clinic')->where($where)->count();
                  if($lat&&$lng){

                    //这里写根据经纬度获取指定距离内的门店数量
                     $clinicListsNear=Db::name('coupons_clinic')->where($where)->select();
                     if($clinicListsNear){
                      $latLng='';
                      //将所有的经纬度组合成一个字符，调用接口
                     foreach ($clinicListsNear as $key => $value) {
                       $latLng.=$value['latitudetext'].','.$value['longitudetext'].';';
                     }
                      //var_dump($clinicListsNear);exit;
                      $latLng=rtrim($latLng,';');
                      $url='http://apis.map.qq.com/ws/distance/v1/?mode=driving&from='.$lat.','.$lng.'&to='.$latLng.'&key=KGMBZ-3YBLD-M7F4F-PAOZ6-DVBC2-UNBFL'; 
                      $result= $this ->http_curl($url);      
                      $result=json_decode($result,true);
                      //var_dump($result);exit;
                      if($result['status']==0){
                        $result2=$result['result']['elements'];
                      }else{
                        $this->error($result['message']);
                      }
                      
                      $data=array_values($clinicListsNear);  

                      foreach($data as $key=>$val){       
                        $data[$key]['distance']=round($result2[$key]['distance']/1000,2);//距离多少千米
                        $data[$key]['duration']=round($result2[$key]['duration']/60);//多少分钟可以到达
                      }
                     }
                     $distance=array();
                      foreach ($data as $V) {
                        $distance[] = $V['distance'];
                      }

                      array_multisort($distance, SORT_ASC, $data);
                      
                      //对数组进行分页
                      //$count=10;
                      //$start=$page*$count; #计算每次分页的开始位置    
                      //$totals=count($data); 
                         
                      //$countpage=ceil($totals/$page); #计算总页面数       
                      //$data=array_slice($data,$start,$count); 
                       $clinicLists['near']=array_slice($data,0,3);
                     //***********************************************************************
                    
                  }else{
                    $clinicLists['near']=[];
                  }
                  if($province){
                      $provinceId=Db::name('area')->where(['name'=>$province,'pid'=>0])->value('id');
                      //var_dump($province);exit;
                      $where['province']=$provinceId;
                      if($city){
                        $cityId=Db::name('area')->where(['name'=>$city,'pid'=>$provinceId])->value('id');
                        $where['city']=$cityId;
                      if($area){
                        $areaId=Db::name('area')->where(['name'=>$area,'pid'=>$cityId])->value('id');
                        $where['area']=$areaId;
                      }
                     }
                  }
                 
                  $clinicLists['lists']=Db::name('coupons_clinic')
                                       ->where('find_in_set('.$categoryCoupon['platform'].',group_ids)')//查询1是否在字段的一个值里面 1,2
                                       ->where($where)
                                       ->field("id,group_ids,name,province,city,area,addresstext,longitudetext,latitudetext,phonetext,logoavatar,weigh")//group_ids 判断是给普通用户可兑换还是给员工，还是给两者都可兑换,对应优惠券的字段platform，1普通，2员工
                                       ->order($order)
                                       ->page($page,$limit)
                                       ->select();
                 // var_dump( $categoryCoupon);exit;
                  }else{
                    $clinicLists['near']=[];
                    $clinicLists['lists']=[]; 
                  }
                

            }else{
              $clinicLists['near']=[];
              $clinicLists['lists']=[];
            }
            
            return $clinicLists;

    }
    /**
     * 腾讯地图crul
     * 
     * 
     */
    public function http_curl($url){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $output = curl_exec($ch);
        if($output === FALSE ){
            echo "CURL Error:".curl_error($ch);
        }
        curl_close($ch);
        return $output;
    }
     /**
     * 三方接口,自动生成优惠券模块
     *
     * @param string $platform 平台，1代表员工系统，,2代表 积分商城
     * @param string $type     优惠券类型，对应后台优惠券类型id
     * @param string $num      生成同类型优惠券数量,默认是1
     * @param string $unionid  积分商城传此参数，唯一识别用户 
     * @param string $name     用户姓名，HR系统传此参数
     * @param string $staffNumber     员工工号，HR系统传此参数
     */
    public function createAutoCoupon($platform=1,$type,$num=1,$unionid=null,$name=null,$staffNumber=null)
    {
          
          $j=1;
          //查询该类型优惠券的有效期
          $coupon_category_effective=Db::name('coupons_category')->where('id',$type)->value('effective');
          $coupon_category_effective=intval($coupon_category_effective);
          $clinic_ids=Db::name('coupons_category')->where('id',$type)->value('clinic_ids');
          $clinic_ids=intval($clinic_ids);
          if(!$coupon_category_effective){
            $this->error('暂无该类型优惠券');
          }
          //设定开始时间未当天领取通过时间
          $begintime=date('Y-m-d',time());
          $endtime=date("Y-m-d", time()+$coupon_category_effective*24*60*60);
         //HR系统过来的数据
         if($platform==1){
             $datas=[
            'coupon_category_id'=>$type,
            'clinic_id'=>$clinic_ids,
            'name'=>$name,
            'staffnumber'=>$staffNumber,
            'platform'=>1,
            'createtime'=>time(),
            'updatetime'=>time(),
            'begintime' =>$begintime,
            'endtime'   =>$endtime
                 ];  
         }
         //积分商城过来的优惠券
         if($platform==2){
           // $isUserExit=Db::name('third')->where('unionid',$unionid)->find();
           // if(!$isUserExit){
           //   $this->error('无此用户信息');
           // }
           $datas=[
            'coupon_category_id'=>$type,
            'unionid'=>$unionid,
            'clinic_id'=>$clinic_ids,
            'platform'=>2,
            'createtime'=>time(),
            'updatetime'=>time(),
            'begintime' =>$begintime,
            'endtime'   =>$endtime
                 ];
            

           }
          //var_dump($num);exit;
          //执行循环插入
          $callbackInfo=[];
          for($i=1;$i<=intval($num);$i++){
            //生成唯一的12位优惠券编码
            $tempsn = unpack('H12',str_shuffle(sha1(uniqid())));
            $datas['number'] = $tempsn[1];
            
            $basic=new Basic;
            $datas['qrcodeimage']=$basic->getQrCode(1,$datas['number'],$datas['coupon_category_id']);
               Db::startTrans();
               $Coupon = new \app\admin\model\coupons\Coupons();
                  try { 
                          $resc=$Coupon->allowField(true)->save($datas);
                            Db::commit();
                            $callbackInfo[$i-1]['coupon_num']=$datas['number'];
                            $callbackInfo[$i-1]['coupon_category_id']=$type;
                            $callbackInfo[$i-1]['begintime']=$begintime;
                            $callbackInfo[$i-1]['endtime']=$endtime;
                            $j++;
                        } catch (ValidateException $e) {
                            Db::rollback();
                            $j--;
                            //$this->error($e->getMessage());
                        } catch (PDOException $e) {
                            Db::rollback();
                            $j--;
                            //$this->error($e->getMessage());
                        } catch (Exception $e) {
                            Db::rollback();
                            $j--;
                            //$this->error($e->getMessage());
                        }
                       
             }
           if ($i==$j) {
               $n=$i-1;
               $res=['status'=>1,'message'=>'优惠券创建成功，共生成'.$n.'条优惠券信息','callbackInfo'=>$callbackInfo];
            } else {
                $res=['status'=>0,'message'=>'优惠券未全部创建成功，需生成'.$i.'条优惠券，成功生成'.$j.'条优惠券信息','callbackInfo'=>$callbackInfo];
             }
            
          return $res;
          //$this->success('返回成功',$res);

    }

    public function createAutoClinicAccount(){
       //门店列
       $clinic = new \app\admin\model\coupons\Clinic();
       $clinicLists= $clinic::where(['user_code'=>''])->select();
       if(count($clinicLists)==0){
         $this->error('暂无需要更新的医院账户信息');
       }
        
       for($i=0;$i<count($clinicLists);$i++){
            //生成唯一的8位医院编号
            $tempsn = unpack('H8',str_shuffle(sha1(uniqid())));
            $datas[$i]['user_code'] ='S'.$tempsn[1];
            $datas[$i]['id']=$clinicLists[$i]['id'];
         }
       $resc=$clinic->allowField(true)->saveAll($datas,true);
       $this->success('更新成功',$resc);  
    }
//主动判断是否HTTPS
  function isHTTPS()
  {
      if (defined('HTTPS') && HTTPS) return true;
      if (!isset($_SERVER)) return FALSE;
      if (!isset($_SERVER['HTTPS'])) return FALSE;
      if ($_SERVER['HTTPS'] === 1) {  //Apache
          return TRUE;
      } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
          return TRUE;
      } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
          return TRUE;
      }
      return FALSE;
    }
/**
 *输出省市区json
 * 
 *
 */
public function areaJson(){
  $province=Db::name('area')->where('pid',0)->select();
  $area=[];
  foreach ($province as $key => $value) {
    $area[$key]['code']=$value['zip'];
    $area[$key]['name']=$value['name'];
    //循环市
    $city=Db::name('area')->where('pid',$value['id'])->select();
    foreach ($city as $k => $v) {
      $area[$key]['code']=$city[0]['zip'];
      $area[$key]['cityList'][$k]['code']=$v['zip'];
      $area[$key]['cityList'][$k]['name']=$v['name'];
      $arealist=Db::name('area')->where('pid',$v['id'])->select();
      foreach ($arealist as $kk => $vv) {
        $area[$key]['cityList'][$k]['areaList'][$kk]['code']=$vv['zip'];
        $area[$key]['cityList'][$k]['areaList'][$kk]['name']=$vv['name'];
      }
    }
  }
  $this->success('返回成功', $area);
}

 //循环查询过期的预约，设定为已过期
   
   public function AppointmentAutoExpired(){
    $time=time();
    //执行当天的最后时间
    $endtime=strtotime(date('Y-m-d 23:59:59',$time));
    $appointmentIds=Db::name('coupons_appointment')->where(['appointmenttime'=>array('lt',$endtime),'statuslist'=>array('in','0')])->column('id');
   if(count($appointmentIds)==0)
     $this->error('未查询到已过期优惠券');
    //要更新的数据表的主键数组
    $where['id']= $appointmentIds;
   //ID主键数组对应的待更新数据
   $save=[];
   for($i=0;$i<count($appointmentIds);$i++){
    $save[]=['statuslist'=>2];
   }
    // $save=array(
    //   array('School'=>'DK Univisity01','isExport'=>0),
    //   array('School'=>'DK Univisity02','isExport'=>0),
    //   array('School'=>'DK Univisity03','isExport'=>0),
    //   array('School'=>'DK Univisity04','isExport'=>0),
    //   array('School'=>'','isExport'=>0),
    //  // array('School'=>'  Univisity05','isExport'=>0),
    // );
    $f=$this->saveAll($where,$save,'coupon_appointment');
    if(count($f['id'])>0){
       //返回更新成功的ID数组
        echo "This is success :</br>";
        dump($f);
        echo 'ok';
    }else{
       //更新失败操作
        echo "This is failed :</br>";
        dump($f);
        echo 'error';
    }
    //$province=Db::name('coupons')->where('endtime','lt',$endtime)->select();
   } 
   
   //循环查询过期的优惠券，设定为已过期
   
   public function couponAutoExpired(){
    $time=time();
    //执行当天的最后时间
    $endtime=strtotime(date('Y-m-d 23:59:59',$time));
    $couponIds=Db::name('coupons')->where(['endtime'=>array('lt',$endtime),'statusdata'=>array('in','0,1')])->column('id');
   if(count($couponIds)==0)
     $this->error('未查询到已过期优惠券');
    //要更新的数据表的主键数组
    $where['id']= $couponIds;
   //ID主键数组对应的待更新数据
   $save=[];
   for($i=0;$i<count($couponIds);$i++){
    $save[]=['statusdata'=>3];
   }
    // $save=array(
    //   array('School'=>'DK Univisity01','isExport'=>0),
    //   array('School'=>'DK Univisity02','isExport'=>0),
    //   array('School'=>'DK Univisity03','isExport'=>0),
    //   array('School'=>'DK Univisity04','isExport'=>0),
    //   array('School'=>'','isExport'=>0),
    //  // array('School'=>'  Univisity05','isExport'=>0),
    // );
    $f=$this->saveAll($where,$save,'coupon');
    if(count($f['id'])>0){
       //返回更新成功的ID数组
        echo "This is success :</br>";
        dump($f);
        echo 'ok';
    }else{
       //更新失败操作
        echo "This is failed :</br>";
        dump($f);
        echo 'error';
    }
    //$province=Db::name('coupons')->where('endtime','lt',$endtime)->select();
   } 
   /*
     *  @param $saveWhere ：想要更新主键ID数组
     *  @param $saveData    ：想要更新的ID数组所对应的数据
     *  @param $tableName  : 想要更新的表明
     *  @param $saveWhere  : 返回更新成功后的主键ID数组
     * */
    public function saveAll($saveWhere,$saveData,$tableName){
        if($saveWhere==null||$tableName==null)
            return false;
        //获取更新的主键id名称
        $key = array_keys($saveWhere)[0];
        //获取更新列表的长度
        $len = count($saveWhere[$key]);
        $flag=true;
        // isset($model)?$model:
        $model =Db::name($tableName);
        //开启事务处理机制
        $model->startTrans();
        //记录更新失败ID
        $error=[];
        for($i=0;$i<$len;$i++){
            //预处理sql语句
            $isRight=$model->where($key.'='.$saveWhere[$key][$i])->update($saveData[$i]);
            if($isRight==0){
                //将更新失败的记录下来
                $error[]=$i;
                $flag=false;
            }
            //$flag=$flag&&$isRight;
        }
        if($flag ){
            //如果都成立就提交
            $model->commit();
            return $saveWhere;
        }elseif(count($error)>0&count($error)<$len){
            //先将原先的预处理进行回滚
            $model->rollback();
            for($i=0;$i<count($error);$i++){
                //删除更新失败的ID和Data
                unset($saveWhere[$key][$error[$i]]);
                unset($saveData[$error[$i]]);
            }
            //重新将数组下标进行排序
            $saveWhere[$key]=array_merge($saveWhere[$key]);
            $saveData=array_merge($saveData);
            //进行第二次递归更新
            $this->saveAll($saveWhere,$saveData,$tableName);
            return $saveWhere;
        }
        else{
            //如果都更新就回滚
            $model->rollback();
            return false;
        }
    }
}
